<%@page import="java.net.URLEncoder"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.BufferedInputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="com.model.StockInfo"%>
<%@page import="com.keen.zx.cn.ExcelUtil"%>
<%@page import="com.keen.util.ConfigUtil"%>
<%@page import="java.util.UUID"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.Iterator"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");

String type = request.getParameter("type");
String resultFilePath = ConfigUtil.getValue("stock_info_result_file_path");
String resultMessage = "";
boolean success = true;
List items = null;
//获取表单数据
try {
	try {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		items = upload.parseRequest(request);
		if(type==null || type.trim().equals("")){
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					if ("type".equals(item.getFieldName())) {
						type = item.getString("GBK");
					}
				}
			}
		}
	} catch (Exception e) {
	}
} catch (Exception e) {
	e.printStackTrace();
}
//处理
if(type!=null && type.trim().equals("cleanResult")){
	try{
		File resultFile = new File(resultFilePath);
		if(resultFile.exists()){
			resultFile.delete();
		}
		resultMessage = "清除成功";
	}catch(Exception e){
		resultMessage = "清除失败！"+e.getMessage();
		success = false;
	}
}else if(type!=null && type.trim().equals("download")){//下载文件
	resultMessage = "";
	FileInputStream fis = null;
	OutputStream os = null;
	try {
		response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode("库存比对结果.xlsx", "UTF-8"));
		response.setContentType("application/msexcel;charset=UTF-8");
		//response.setContentType("application/octet-stream");
		//response.setHeader("Content-Disposition", "attachment;filename=\"库存比对结果.xlsx\"");
		String path = ConfigUtil.getValue("stock_info_result_file_path");
		fis = new FileInputStream(path);

		int len = 0;
		byte buffer[] = new byte[1024 * 1000];
		os = response.getOutputStream();
		while ((len = fis.read(buffer)) > 0) {
			os.write(buffer, 0, len);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if(os!=null){
			os.close();
		}
		if(fis!=null){
			fis.close();
		}
	}
}else if(type!=null && type.trim().equals("deal")){//处理文件
	//接收保存库存文件
	String sourceFilePath = "";
	String distFilePath = "";
	resultMessage = "处理成功！";
	if(success){
		String arrowType = ConfigUtil.getValue("upload_file_arrow");
		try {
			// List items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			int n = 0;

			String dir = ConfigUtil.getValue("upload_file_path");
			
			File tempdir = new File(dir);
			if (!(tempdir.exists())) {
				tempdir.mkdirs();
			}
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.getName() != null && !item.getName().equals("")) {
					n = n + 1;

					File tempFile = new File(item.getName());
					String ex = item.getName().substring(item.getName().lastIndexOf(".")).toLowerCase();

					boolean flag3 = false;

					String tempList[] = arrowType.split(";");
					for (int i = 0; i < tempList.length; i++) {
						if (ex.toUpperCase().endsWith(tempList[i].toUpperCase())) {
							flag3 = true;
							break;
						}
					}

					if (flag3) {
						flag3 = false;
						if (ex.toLowerCase().equals(".xls")) {
							if (item.getContentType().equals("application/vnd.ms-excel")
									||item.getContentType().equals("application/octet-stream")) {
								flag3 = true;
							}
						}

						if (ex.toLowerCase().equals(".xlsx")) {
							if (item.getContentType().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") 
									||item.getContentType().equals("application/octet-stream")) {
								flag3 = true;
							}
						}
					}

					if (flag3) {
						String fileName = dir + "/" + UUID.randomUUID() + ex;
						if ("file1".equals(item.getFieldName())){
							sourceFilePath = fileName;
						}else if ("file2".equals(item.getFieldName())){
							distFilePath = fileName;
						}
						File file = new File(fileName);
						item.write(file);
					} else {
						resultMessage = "此文件不允许上传！" + item.getName() + " " + item.getContentType() + " " + item.getSize();
						success = false;
					}
				}
			}
			if(n<2){
				resultMessage = "没有选择上传文件！";
				success = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			success = false;
			resultMessage = "上传文件失败！"+e.getMessage();
		}
	}
	//比对两个文件
	File file1 = new File(sourceFilePath);
	File file2 = new File(distFilePath);
	List<StockInfo> stockInfos2 = null;//最后合并后的
	if(success){
		if(sourceFilePath != null && !sourceFilePath.trim().equals("") && 
				distFilePath != null && !distFilePath.trim().equals("")){
			InputStream sourceIs = new FileInputStream(file1);
			InputStream disIs = new FileInputStream(file2);
			try{
				List<StockInfo> stockInfos1 = ExcelUtil.readStockInfo(ConfigUtil.getValue("stock_info_xml_conf"), sourceIs);
				stockInfos2 = ExcelUtil.readStockInfo(ConfigUtil.getValue("stock_info_xml_conf"), disIs);
				if(stockInfos1==null || stockInfos1.size()<=0 || 
						stockInfos2==null || stockInfos2.size()<=0){
					throw new IllegalStateException("无数据或工作表（Sheet）名必须为:keen1");
				}
				//将需要匹配到目标表的源表装Map
				Map<String, StockInfo> sourceMap = new HashMap();
				for(StockInfo stockInfo1:stockInfos1){
					sourceMap.put(stockInfo1.getFittingCode1(), stockInfo1);
				}
				//比对
				for(StockInfo stockInfo2:stockInfos2){
					if(sourceMap.keySet().contains(stockInfo2.getFittingCode1())){
						StockInfo stockInfo1 = sourceMap.get(stockInfo2.getFittingCode1());
						stockInfo2.setFittingCode2(stockInfo1.getFittingCode1());
						stockInfo2.setStockCode2(stockInfo1.getStockCode1());
						stockInfo2.setStockCount2(stockInfo1.getStockCount1());
						stockInfo2.setPrice2(stockInfo1.getPrice1());
						//计算差值
						try{
							Long count1 = "".equals(stockInfo2.getStockCount1())?0:Long.parseLong(stockInfo2.getStockCount1());
							Long count2 = "".equals(stockInfo2.getStockCount2())?0:Long.parseLong(stockInfo2.getStockCount2());
							stockInfo2.setStockCountDiff((count2-count1)+"");
						}catch(NumberFormatException e){
							stockInfo2.setStockCountDiff( "NaN" );
						}
						//移出Map
						sourceMap.remove(stockInfo2.getFittingCode1());
					}
				}
				//剩下在表1（源表）中无的数据也放在一起
				for(StockInfo stockInfo1:stockInfos1){
					if(sourceMap.keySet().contains(stockInfo1.getFittingCode1())){
						StockInfo stockInfoNew = new StockInfo();
						stockInfoNew.setFittingCode2(stockInfo1.getFittingCode1());
						stockInfoNew.setStockCode2(stockInfo1.getStockCode1());
						stockInfoNew.setStockCount2(stockInfo1.getStockCount1());
						stockInfoNew.setPrice2(stockInfo1.getPrice1());
						stockInfos2.add(stockInfoNew);
					}
				}
			}catch(Exception e){
				success = false;
				resultMessage = e.getMessage();
			}finally{
				if(sourceIs!=null){
					sourceIs.close();
				}
				if(disIs!=null){
					disIs.close();
				}
				//处理结束删除文件
				if(file1.exists()){
					file1.delete();
				}
				if(file2.exists()){
					file2.delete();
				}
			}
		}else{
			success = false;
			System.out.println("上传写入文件没有成功！");
		}
	}else{//至少有一个文件不存在时，删除存在文件
		//处理结束删除文件
		if(file1.exists()){
			file1.delete();
		}
		if(file2.exists()){
			file2.delete();
		}
	}
	
	//生成合并后文件
	if(success && stockInfos2!=null && stockInfos2.size()>0){
		List<List<StockInfo>> data = new ArrayList();
		data.add(stockInfos2);
		ExcelUtil.exportSheets(data, 
				Thread.currentThread().getContextClassLoader().getResourceAsStream(ConfigUtil.getValue("stock_template_xls")), 
				resultFilePath, 
				new HashMap());
	}
}
if(resultMessage!=null && !resultMessage.trim().equals("")){
	resultMessage = "alert(\""+resultMessage+"\");";
}

//检查结果文件是否存在
boolean isResultExist = new File(resultFilePath).exists();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>库存比对</title>
</head>
<body>
<form id="form1" name="form1" action="index.jsp" enctype="multipart/form-data" method="post" >
<div>
将文件：<input type="file" id="file1" name="file1"/>
</div>
<div>
合并到：<input type="file" id="file2" name="file2"/>
</div>
<div>
<div style="display:none">
<input type="text" id="type" name="type" value="download"/>
</div>
<input type="button" value="处理" onclick="deal()"/>
</div>
<div style="display:<%=isResultExist?"":"none" %>">
输出文件：<a href="javascript:download()">点击下载</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:cleanResult()">清除结果文件</a>
</div>
</form>
<script type="text/javascript">
//提交处理
function deal(){
	document.getElementById("type").value="deal";
	form1.submit();
}
//下载
function download(){
	location = "index.jsp?type=download";
}
//清除结果文件
function cleanResult(){
	location = "index.jsp?type=cleanResult";
}
<%=resultMessage%>
</script>
</body>
</html>